const path = require("path");
const { isArray, clone } = require("xe-utils");
const fs = require("fs-extra");
const axios = require("axios");
const dependencies = require("../dependencies.cdn.js");
fs.ensureLinkSync();

__main__();

function __main__() {
  // downloadDependencies();
  appendLocalDependencies();
}

function klk(fileList1) {
  fileList1.forEach((l3) => {
    downloadFile(l3);
  });
}

function downloadDependencies() {
  fs.ensureDirSync(path.join(__dirname, "../public/static"));
  const fileList = getFileList();
  klk(fileList);
}

function getFileList() {
  const arr = [];
  dependencies.forEach((item) => {
    if (item.js) {
      if (isArray(item.js)) {
        arr.push(...item.js);
      } else {
        arr.push(item.js);
      }
    }
    if (item.css) {
      arr.push(item.css);
    }
  });
  return arr;
}

function getFileNameByUrl(url) {
  const basename = path.basename(url);
  const libName = /https:\/\/unpkg.com\/([^/]*)/.exec(url)[1];
  return `${libName}-${basename}`;
}

function downloadFile(url) {
  axios.get(url, { responseType: "stream" }).then((res) => {
    const fileName = getFileNameByUrl(url);
    const filePath = path.join(__dirname, "../public/static", fileName);
    console.log("downloadFile", { url, fileName, filePath });
    res.data.pipe(fs.createWriteStream(filePath));
  });
}

function appendLocalDependencies() {
  const map = getFileList().reduce((map, url) => {
    const fileName = getFileNameByUrl(url);
    map[url] = `static/${fileName}`;
    return map;
  }, {});
  appendLocalUrl(map);
}

function appendLocalUrl(map) {
  dependencies.forEach((dep) => {
    if (dep.js) {
      if (isArray(dep.js)) {
        dep._js = dep.js.map((url) => map[url]);
      } else {
        dep._js = map[dep.js];
      }
    }
    if (dep.css) {
      dep._css = map[dep.css];
    }
  });

  const filePath = path.join(__dirname, "../dependencies.cdn.js");
  const content = `module.exports = ${JSON.stringify(dependencies, null, 2)}`;
  fs.writeFileSync(filePath, content);
}
